// pages/home/home.js
import {
  getBanner,
  getMusicPlayUrl,
  getNewMusicList
} from "./../../api/music.js"
const canvas = require('./PlayBtnCanvas.js')


//音乐播放器
const audioAudioCtx = wx.createInnerAudioContext()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    navigateHeight: 40,
    statusBarHeight: 20,
    scrollHeight: 0,
    sysInfo: null,
    viewpageHeight: 150,
    selectTab: 0, //选中的tabbar
    isScrollY: false, //默认scroll-view 不能滑动
    banners: {
      loading: true,
      urls: []
    }, //轮播图
    songs: [{
        loading: true,
        list: [], //请求到的数据
        show: [] //显示的数据
      }, //全部
      {
        loading: true,
        list: [], //请求到的数据
        show: [] //显示的数据
      }, //华语
      {
        loading: true,
        list: [], //请求到的数据
        show: [] //显示的数据
      }, //欧美
      {
        loading: true,
        list: [], //请求到的数据
        show: [] //显示的数据
      }, //日本
      {
        loading: true,
        list: [], //请求到的数据
        show: [] //显示的数据
      } //韩国
    ], //歌曲
    currentMusic: {
      img: "",
      name: "",
      index: -1,
      tab: -1,
      progress: 0,
      status: 0, //0 暂停 1 播放 
    }, //当前正在播放的音乐
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    //获取右侧胶囊位置
    let menu = wx.getMenuButtonBoundingClientRect()
    //获取系统参数
    this.data.sysInfo = wx.getSystemInfoSync()
    const statusBarHeight = this.data.sysInfo.statusBarHeight
    const navigateHeight = menu.bottom + (menu.top - statusBarHeight)
    this.setData({
      menu: menu,
      navigateHeight: navigateHeight,
      statusBarHeight: statusBarHeight,
    })
    //获取组件信息
    const query = wx.createSelectorQuery()

    query.select('.tabbar').boundingClientRect()
    query.selectViewport().scrollOffset()
    let that = this
    query.exec(function (res) {
      console.log('query', res)
      that.data.tabbarY = res[0].top - that.data.navigateHeight;
      let height = that.data.sysInfo.screenHeight - that.data.navigateHeight + (that.data.tabbarY);
      console.log("height", height)
      that.setData({
        scrollHeight: that.data.sysInfo.screenHeight - that.data.navigateHeight,
        viewpageHeight: height - (that.data.tabbarY - res[0].height)
      })
    })

    //请求
    getBanner().then(res => {
      that.setData({
        banners: {
          loading: false,
          urls: res
        }
      })
    })

    this.requestSong(0, 0)

    canvas.init(this.data.sysInfo.pixelRatio)
    this.initAudio()
  },
  //初始化音乐播放器
  initAudio() {
    audioAudioCtx.onPlay((res) => {

      console.log("开始播放")
      this.data.currentMusic.status = 1
      canvas.drawCanvas(1, 0)
      this.setData({
        ['currentMusic.status']: 1
      })
    })

    audioAudioCtx.onWaiting(() => {

      console.log('播放等待!');
    })
    //音频准备就需回调
    audioAudioCtx.onCanplay(() => {
      audioAudioCtx.pause()
      audioAudioCtx.play()
      console.log('播放就绪!');
    })
    //播放结束回调
    audioAudioCtx.onEnded((res) => {
      console.log('播放结束!');
      this.data.currentMusic.progress = 0
      this.data.currentMusic.status = 0
      this.setData({
        ['currentMusic.status']: 0
      })
      canvas.drawProgress(0)
    })
    //播放错误回调
    audioAudioCtx.onError((res) => {
      console.log('播放音频失败', res);
      // canvas.drawCanvas(0,0)
    })
    //播放时间进度回调
    audioAudioCtx.onTimeUpdate(() => {
      this.data.currentMusic.progress = (audioAudioCtx.currentTime / audioAudioCtx.duration)
      canvas.drawProgress(this.data.currentMusic.progress)
    })

    audioAudioCtx.onPause(() => {
      console.log('暂停音频');
      this.data.currentMusic.status = 0
      this.setData({
        ['currentMusic.status']: 0
      })
      canvas.drawCanvas(0, this.data.currentMusic.progress)
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  //tab 切换
  onTabChange(e) {
    let index = e.currentTarget.dataset.index
    this.setData({
      selectTab: index
    })
  },
  //页面切换
  onPageChange(e) {
    let index = e.detail.current
    let type = e.detail.currentItemId
    let source = e.detail.source
    if (source == "touch") {
      this.setData({
        selectTab: index
      })
    }
    if (this.data.songs[index].show == 0) {
      this.requestSong(index, type)
    }
  },
  //获取歌曲
  requestSong(index, type) {
    let that = this
    console.log("start")
    getNewMusicList(type).then(list => {
      /**
              * {
             loading: true,
             list:[],//请求到的数据
             show:[] //显示的数据
           }
              */
      const item = that.data.songs[index]
      item.list = list
      item.show = list.splice(0, 20)
      item.loading = false
      if (index === that.data.selectTab) {
        let page = 'songs[' + index + "]"
        that.setData({
          [page]: item
        })
        console.log("刷新")
      }
    })
  },
  //底部 播放暂停点击
  onPalyStatus(e) {
    console.log("点击Canvas")
    if (this.data.currentMusic.status == 0) {
      audioAudioCtx.play()
    } else if (this.data.currentMusic.status == 1) {
      audioAudioCtx.pause()
    } else {}

  },
  //音乐item点击
  onMusicClick(e) {
    let index = e.currentTarget.dataset.index
    let selectTab = e.currentTarget.dataset.tab
    let item = this.data.songs[selectTab].show[index]
    if (item.mp3Url != null) {
      //存储信息
      this.setData({
        currentMusic: {
          img: item.albumPic,
          name: item.name + item.alias,
          index: index,
          tab: selectTab,
          progress: 0,
          status: 1, //0 暂停 1 播放 
        },
      })

      audioAudioCtx.src = item.mp3Url
      audioAudioCtx.play()
    } else {
      const that = this
      getMusicPlayUrl(item.id).then(res => {
        const mp3Url=res
        console.log("mp3",mp3Url)
        //存储信息
        that.setData({
          currentMusic: {
            img: item.albumPic,
            name: item.name + item.alias,
            index: index,
            tab: selectTab,
            progress: 0,
            status: 1, //0 暂停 1 播放 
          },
          ['songs[' + selectTab + '].show[' + index + '].mp3Url']: mp3Url
        })

        audioAudioCtx.src = mp3Url
        audioAudioCtx.play()
      }).catch(res => {
        wx.showToast({
          title: res,
          icon: "error"
        })
      })

    }
  },
  //滑动到底部
  onScrollToLower() {
    console.log("onScrollToLower")
    const item = this.data.songs[this.data.selectTab]
    let page = 'songs[' + this.data.selectTab + "]"
    item.show = item.show.concat(item.list.splice(0, 20))
    this.setData({
      [page]: item
    })
  },
  //滑动到顶部
  onScrollToUpper(e) {
    console.log("滑动到顶部", e)

  },
  onScroll(e) {
    console.log("onScroll:" + this.data.isScrollY + " ", e)
    const id = e.currentTarget.id
    const scrollY = e.detail.scrollTop
    const isScrollY = this.data.isScrollY
    if (id === 'root') {
      if (scrollY >= this.data.tabbarY) {
        if (!isScrollY) {
          console.log("开启滑动")
          this.setData({
            isScrollY: true
          })
        }
      } else {
        if (isScrollY) {
          console.log("禁止滑动")
          this.setData({
            isScrollY: false
          })
        }
      }
    } else if (id === 'child') {
      if (scrollY == 0) {
        this.setData({
          isScrollY: false
        })
      }
    }

  },

})